﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JTParcrelHelper.MessageClient
{
    public class CheckStatus
    {
        public static bool IsHostConn(string host, int port, int millisecondsTimeout)
        {
            if (String.IsNullOrEmpty(host) || !DataValid.IsIPAddr(host))
            {
                return false;
            }

            if (millisecondsTimeout < 0 || millisecondsTimeout > 10 * 1000)
            {
                millisecondsTimeout = 100;
            }

            using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
            {
                try
                {
                    IAsyncResult ar = client.BeginConnect(host, port, null, null);
                    ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
                    return client.Connected;
                }
                catch (Exception ex)
                {
                    //Logger.LogFatal("CheckStatus.IsHostConn", "CheckStatus.IsHostConn()方法捕获致命异常:" + ex.Message);
                    return false;
                }
                finally
                {
                    try { client.Close(); }
                    catch {; }
                }
            }
        }

        public static bool IsIPConn(string ip, int timeout)
        {
            System.Net.NetworkInformation.Ping pingSender = null;
            System.Net.NetworkInformation.PingReply reply = null;
            bool pingResult = false;

            if (!DataValid.IsIPAddr(ip))
            {
                return false;
            }

            if (timeout < 0 || timeout > 10 * 1000)
            {
                timeout = 100;
            }

            using (pingSender = new System.Net.NetworkInformation.Ping())
            {
                try
                {
                    reply = pingSender.Send(ip, timeout);
                }
                catch (Exception ex)
                {
                    //Logger.LogError(null, "PING命令异常:" + ex.Message);
                }
                finally
                {
                    if (reply != null && reply.Status == System.Net.NetworkInformation.IPStatus.Success)
                    {
                        pingResult = true;
                    }
                    else
                    {
                        pingResult = false;
                    }
                    pingSender.Dispose();
                }
            }
            return pingResult;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////End Of Class
    }
}
